﻿using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using UI.ExamplePanel;

public class DialogManager : Singleton<DialogManager>
{
    [Header("对话UI组件")]
    public Image dialogBubble;
    public GameObject dialoguePanel;

    public GameObject dialogGuest;
    public TextMeshProUGUI speakerText;
    public TextMeshProUGUI dialogText;
    public Button nextGuestBtn;         // 点击推进按钮

    public GameObject dialogNarrator;
    public TextMeshProUGUI narratorText;
    public Button nextNarratorBtn;      // 点击推进按钮

    public GameObject cardListContent;

    [Header("对话设置")]
    public float defaultTextSpeed = 0.05f;
    public float autoAdvanceDelay = 2.0f;

    private DialogueConfig dialogueConfig;
    private Dictionary<string, List<DialogueGroup>> characterDialogues;

    private Coroutine currentDialogueCoroutine;
    private DialogueGroup currentDialogueGroup;
    private int currentDialogueIndex;

    private bool isTyping = false;     // 当前是否正在打字
    private bool isFullShown = false;  // 当前句子是否已完整显示
    private bool clicked = false;      // 是否点击过
    private bool isPlayerSpeaking = false;
    private bool isDarkBubble = false;

    public bool isDialogEnd { get; private set; } = false;
    public bool IsDialoguePlaying { get; private set; } = false;

    private void Awake()
    {
        LoadDialogueConfig();
        InitializeCharacterDialogues();
    }

    private void Start()
    {
        if (nextGuestBtn != null)
            nextGuestBtn.onClick.AddListener(OnNextButtonClicked);
        if (nextNarratorBtn != null)
            nextNarratorBtn.onClick.AddListener(OnNextButtonClicked);
    }

    #region 初始化与加载配置
    private void LoadDialogueConfig()
    {
        TextAsset jsonFile = Resources.Load<TextAsset>("Dialogs");
        if (jsonFile != null)
        {
            dialogueConfig = JsonUtility.FromJson<DialogueConfig>(jsonFile.text);
            Debug.Log($"对话配置加载成功！共 {dialogueConfig.dialogueGroups.Count} 组对话");
        }
        else
        {
            Debug.LogError("对话配置文件加载失败！");
        }
    }

    private void InitializeCharacterDialogues()
    {
        characterDialogues = new Dictionary<string, List<DialogueGroup>>();
        foreach (var group in dialogueConfig.dialogueGroups)
        {
            if (!characterDialogues.ContainsKey(group.character))
                characterDialogues[group.character] = new List<DialogueGroup>();

            characterDialogues[group.character].Add(group);
        }
    }
    #endregion

    #region 外部接口

    public void StartRandomDialogueForCharacter(string characterName, Transform myPanel)
    {
        if (characterDialogues.ContainsKey(characterName) && characterDialogues[characterName].Count > 0)
        {
            int randomIndex = Random.Range(0, characterDialogues[characterName].Count);
            StartDialogueGroup(characterDialogues[characterName][randomIndex], myPanel);
        }
        else
        {
            Debug.LogWarning($"角色 {characterName} 没有可用的对话！");
            EndDialogue();
        }
    }

/// <summary>
/// 调用角色或卡片对应对话
/// </summary>
/// <param name="characterName">角色</param>
/// <param name="cardIndex">卡片id</param>
/// <param name="myPanel">挂载的Panel位置/</param>
/// <param name="isDarkBubble">是否黑色气泡</param>
    public void StartDialogueForCharacter(string characterName, int cardIndex, Transform myPanel, bool isDarkBubble = false)
    {
        if (characterDialogues.ContainsKey(characterName) && cardIndex < characterDialogues[characterName].Count)
        {
            this.isDarkBubble = isDarkBubble;
            StartDialogueGroup(characterDialogues[characterName][cardIndex], myPanel);
        }
        else
        {
            Debug.LogWarning($"角色 {characterName} 没有可用的对话！");
            EndDialogue();
        }
    }

    public string SetDialogFromCharacterAndID(string characterName, int cardID)
    {
        //只有一个文本，直接访问
        var specialCardDialog = characterDialogues[characterName][cardID].dialogueSet[0].text;
        return specialCardDialog;
    }

    public bool IsDialogueActive() => IsDialoguePlaying;

    #endregion

    #region 播放核心逻辑
    private void StartDialogueGroup(DialogueGroup group, Transform myPanel)
    {
        if (currentDialogueCoroutine != null)
            StopCoroutine(currentDialogueCoroutine);

        currentDialogueGroup = group;
        currentDialogueIndex = 0;
        isDialogEnd = false;
        isPlayerSpeaking = false;
        IsDialoguePlaying = true;
        dialoguePanel.SetActive(true);
        dialoguePanel.transform.parent = myPanel;
        cardListContent.SetActive(false);

        if (myPanel.GetComponent<BlackPanel>())
        {
            currentDialogueCoroutine = StartCoroutine(PlayDialogueSequence(true));
        }
        else
        {
            currentDialogueCoroutine = StartCoroutine(PlayDialogueSequence());
        }

    }

    private IEnumerator PlayDialogueSequence(bool isBlack = false)
    {
        Debug.Log($"开始播放 {currentDialogueGroup.character} 的第 {currentDialogueGroup.id} 组对话");

        // 播放玩家对话
        if (currentDialogueGroup.playerDialogueSet != null)
        {
            foreach (var d in currentDialogueGroup.playerDialogueSet)
            {
                isPlayerSpeaking = true;
                yield return StartCoroutine(PlaySingleDialogue(d, "铃铛", isBlack));
            }
        }

        // 播放NPC对话
        if (currentDialogueGroup.dialogueSet != null)
        {
            foreach (var d in currentDialogueGroup.dialogueSet)
            {
                isPlayerSpeaking = false;
                yield return StartCoroutine(PlaySingleDialogue(d, currentDialogueGroup.character, isBlack));
            }
        }

        EndDialogue();
    }

    private IEnumerator PlaySingleDialogue(DialogueData dialogue, string speaker, bool isBlack = false)
    {
        // 显示说话者
        speakerText.text = speaker;

        dialogNarrator.SetActive(isBlack);
        dialogGuest.SetActive(!isBlack);

        // 设置气泡
        dialogBubble.sprite = Resources.Load<Sprite>(!isDarkBubble
            ? "Arts/Bubbles/bubble"
            : "Arts/Bubbles/dark_Bubble");

        // 显示表情
        GamePanel.Instance.GetGuestEmoji(speaker, dialogue.emotion);

        // 打字效果
        yield return StartCoroutine(TypeText(dialogue.text, isBlack));

        // 等待点击推进
        yield return StartCoroutine(WaitForNextClick(autoAdvanceDelay));
    }

    #endregion

    #region 打字与点击逻辑

    private IEnumerator TypeText(string text, bool isBlack)
    {
        isTyping = true;
        isFullShown = false;
        if (isBlack)
        {
            narratorText.text = "";

            foreach (char c in text)
            {
                if (isFullShown) break; // 若玩家点击提前显示完
                narratorText.text += c;
                yield return new WaitForSeconds(defaultTextSpeed);
            }
            narratorText.text = text;
        }
        else
        {
            dialogText.text = "";

            foreach (char c in text)
            {
                if (isFullShown) break; // 若玩家点击提前显示完
                dialogText.text += c;
                yield return new WaitForSeconds(defaultTextSpeed);
            }
            dialogText.text = text; // 确保完整显示
        }
        isTyping = false;
        isFullShown = true;
    }

    private IEnumerator WaitForNextClick(float waitTime)
    {
        clicked = false;
        float timer = 0f;

        while (timer < waitTime && !clicked)
        {
            timer += Time.deltaTime;
            yield return null;
        }
    }

    // 点击事件逻辑
    private void OnNextButtonClicked()
    {
        if (isTyping)
        {
            // 如果还在打字，第一次点击 → 立刻显示全部文字
            isFullShown = true;
        }
        else
        {
            // 第二次点击（文字已显示完）→ 跳过等待时间，进入下一句
            clicked = true;
        }
    }

    #endregion

    #region 结束与事件
    public event System.Action OnDialogueFinished;

    private void EndDialogue()
    {
        dialoguePanel.SetActive(false);
        cardListContent.SetActive(true);
        GamePanel.Instance.GetGuestEmoji(null, null);

        Debug.Log("对话结束");

        currentDialogueGroup = null;
        currentDialogueIndex = 0;
        isPlayerSpeaking = false;
        IsDialoguePlaying = false;
        isDialogEnd = true;

        OnDialogueFinished?.Invoke();
    }
    #endregion
}
